# - 利用`Python`实现一个多线程程序
# - 将多线程程序改为多进程程序
import requests
import time
from threading import Thread
from multiprocessing import Process


def my_spend_time(func):   # 装饰器计算运行时间
    def wrapper(*args, **kwargs):
        stat_time = time.time()
        my_result = func(*args, **kwargs)
        end_time = time.time()
        print(f"{func.__name__}运行时间为:{format(end_time - stat_time, '.2f')}s")
        return my_result
    return wrapper


result = []


def request_zhihu(index):
    time.sleep(2)
    url = "https://www.zhihu.com/"  # 访问知乎
    # body = ""
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36"
    }
    response = requests.get(url=url, headers=headers)
    print(f"当前请求序号{index},返回状态码:{response.status_code}")
    result.append(response)


@my_spend_time
def my_thread():
    thread_array = []
    for i in range(5):
        t = Thread(target=request_zhihu, args=(i, ))
        thread_array.append(t)
        t.start()
    for t in thread_array:
        t.join()
    print("多线程已完成!")
    print(result)


@my_spend_time
def my_process():
    process_array = []
    for i in range(5):
        p = Process(target=request_zhihu, args=(i, ))
        process_array.append(p)
        p.start()
    for p in process_array:
        p.join()
    print("多进程已完成!")
    print(result)


if __name__ == "__main__":
    my_thread()
    my_process()
